package plugin;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class ComSearchUPCPlugin implements IProductIDPlugin {

	private String accessToken = "60306184-9295-4D2E-B434-0C7149B46E16";
	private String csvRequest = "1";
	//private String jsonRequest = "3";
	private String searchURL = "http://www.searchupc.com/handlers/upcsearch.ashx";
	private final int ONE_SECOND = 1000;
	
	/**
	 * Default no-arg constructor
	 */
	public ComSearchUPCPlugin() {
		
	}
	
	@Override
	public String identifyProduct(String barcode) throws Exception {
		StringBuilder sb = new StringBuilder();
		sb.append(searchURL).append("?");
		sb.append("request_type=").append(csvRequest);
		sb.append("&access_token=").append(accessToken);
		sb.append("&upc=").append(barcode);
		URL url = new URL(sb.toString());
		URLConnection conn = url.openConnection();
		conn.setConnectTimeout(ONE_SECOND);
		conn.setReadTimeout(ONE_SECOND * 5); //it takes a while sometimes...
		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
		in.readLine(); //skip csv header
		String csv = in.readLine();
		if (csv == null) {
			throw new Exception("Product not found or barcode invalid.");
		}
		int beginQuote = csv.indexOf('"');
		int endQuote = csv.indexOf('"', beginQuote + 1);
		return csv.substring(beginQuote + 1, endQuote);
	}

}
